<template>
  <div id="shareView">
    <div class="header">
      <span class="titleTxt">受邀托管的项目列表</span>
      <a-input-search
        placeholder="项目名称\项目备注\项目组织"
        style="width: 300px"
        v-model.trim="searchKey"
      />
    </div>
    <a-spin :spinning="spinning" tip="进入中...">
      <rj-table
        class="shareNetTable"
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :rowKey="(row) => row.groupId"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <div class="columnsName" slot="projectName" slot-scope="text, record">
          <div
            class="row-name"
            :title="text"
            @click="() => gotoProject(record)"
          >
            {{ text }}
          </div>
          <div class="row-info">
            <div class="infoBlock">
              {{
                record.operation == 3
                  ? '读写'
                  : record.operation == 1
                  ? '只读'
                  : '只写'
              }}
            </div>
            <div class="infoBlock">
              有效期至：{{
                record.expiredAt == 2145974399000
                  ? '永久'
                  : new Date(record.expiredAt).Format('YYYY-MM-DD HH:mm:ss')
              }}
            </div>
            <div class="infoBlock orgBlockStyle" :title="record.tenantName">
              <div class="orgBlock">
                组织：
                <rj-edittablecell
                  title="设置组织名称"
                  placeholder="设置组织名称"
                  :value="record.tenantName"
                  :record="record"
                  :checkRules="[
                    {
                      required: true,
                      message: '请输入组织名称',
                    },
                    {
                      validator: checkTenatName,
                    },
                  ]"
                  @change="tenantChange(record, $event)"
                ></rj-edittablecell>
              </div>
            </div>
          </div>
        </div>
        <template slot="projectRemark" slot-scope="text, record">
          <div class="remarkColumns" :title="record.remark">
            <rj-edittablecell
              title="设置网络备注"
              placeholder="设置网络备注"
              :scroll="{ x: true }"
              :value="record.remark"
              :record="record"
              :checkRules="[
                {
                  validator: checkRemarkName,
                },
              ]"
              @change="remarkChange(record, $event)"
            >
            </rj-edittablecell>
          </div>
        </template>
        <template slot="projectReviceTime" slot-scope="text, record">
          {{
            (record.receiveTime &&
              new Date(record.receiveTime).Format('YYYY-MM-DD hh:mm:ss')) ||
            '-'
          }}
        </template>
        <div class="columnsAction" slot="action" slot-scope="text, record">
          <a-space>
            <a href="javascript:;" @click="() => unShare(record)">
              <icon-font type="ic-share" />
              不再管理
            </a>
            <a href="javascript:;" @click="() => gotoProject(record)">
              进入项目
            </a>
          </a-space>
        </div>
      </rj-table>
    </a-spin>
  </div>
</template>

<script>
import { requestHttp, maccApi, request } from '@utils/index';
import { RjTable, RjEdittablecell, RjModal } from '@components';
import { mapState } from 'vuex';
import lodash from 'lodash';

const columns = [
  {
    title: '项目名称',
    align: 'center',
    dataIndex: 'groupName',
    key: 'groupName',
    width: '30%',
    scopedSlots: { customRender: 'projectName' },
  },
  {
    title: '项目备注',
    align: 'center',
    dataIndex: 'remark',
    key: 'remark',
    width: '25%',
    scopedSlots: { customRender: 'projectRemark' },
  },
  {
    title: '接收时间',
    align: 'center',
    dataIndex: 'receiveTime',
    key: 'receiveTime',
    scopedSlots: { customRender: 'projectReviceTime' },
  },
  {
    title: '操作',
    align: 'center',
    width: 200,
    dataIndex: 'action',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    // fixed: 'right',
  },
];
export default {
  data() {
    return {
      tableData: [],
      loading: false,
      searchKey: '',
      columns: columns,
      pageNum: 1,
      pageSize: 10,
      spinning: false,
      pagination: {
        total: 0,
        showSizeChanger: false,
        showQuickJumper: false,
      },
    };
  },
  components: {
    'rj-table': RjTable,
    'rj-edittablecell': RjEdittablecell,
  },
  computed: {
    ...mapState('User', ['tenantId', 'rootTenantId']),
    ...mapState('Group', ['groupId']),
    ...mapState('Layout', ['newVueFrame']),
    ...mapState('Theme', ['theme']),
  },
  async mounted() {
    await this.getShareNetList();
    if (this.newVueFrame) {
      this.selectFirstGroupTenant();
    } else {
      if (top.location.hash.indexOf('monitor_overview_global_menu') != -1) {
        //父页面的hash值是在首页的话，才把列表第一个租户设置为默认租户（防止进入到“受邀托管项目组” 进入到非首页的页面后，刷新当前页面，导致原先选中的网络又被切换到列表第一个租户）
        this.selectFirstGroupTenant();
      }
    }
  },
  methods: {
    async getShareNetList() {
      this.loading = true;
      const { pageNum, pageSize, searchKey } = this;
      let api = `${maccApi.GET_ALL_SHARE_NET_LIST_API}`;
      api += `?pageNum=${pageNum}&pageSize=${pageSize}`;

      if (searchKey) {
        api += '&searchKey=' + encodeURI(searchKey);
      }
      const {
        code,
        msg = '获取受邀托管项目列表失败',
        sharedGroupList = [],
        count = 0,
      } = await requestHttp({
        api: api,
        method: 'GET',
      });
      this.loading = false;
      if (code != 0) {
        this.$message.error(msg);
        return false;
      }
      this.tableData = sharedGroupList || [];
      this.pagination.total = count || 0;
      return true;
    },

    keySearchProject: lodash.debounce(function () {
      this.getShareNetList();
    }, 500),

    //设置选中第一个网络的租户为当前租户
    async selectFirstGroupTenant() {
      if (!this.tableData || this.tableData.length == 0) {
        //当没有受邀托管项目了，切换到根租户
        if (!this.rootTenantId) return;
        const { code, msg = '切换租户失败' } = await requestHttp({
          api: maccApi.SWICH_ACCOUNT.replace('{tenantId}', this.rootTenantId),
          method: 'GET',
        });
        if (code != 0) {
          this.$message.error(msg);
        } else {
          sessionStorage.clear();
          if (!this.newVueFrame) {
            top.location.reload();
          } else {
            window.location.reload();
          }
        }
        return;
      }
      if (!this.newVueFrame) {
        const { groupId, tenantId } = this.tableData[0];
        this.$iframeMsg('SWITCH_TENANT_UPDATE', {
          groupId,
          tenantId,
        });
      } else {
        const { tenantId, groupId } = this.tableData[0];
        this.$store.commit('Group/SET_GROUPID', groupId);
        // await this.$store.dispatch('User/getTenantInfo'); //更新用户信息
        // await store.dispatch('User/getUserInfo'); //更新用户信息
        // $store.dispatch("Group/getGroupTree");
      }
    },

    handleTableChange(pagination, filters, sorter) {
      const { total } = pagination;
      this.pageNum = pagination.current;
      this.pagination.total = total;
      this.getShareNetList();
    },

    //不再管理
    unShare(record) {
      const self = this;
      const { groupId, tenantId, groupName } = record;
      RjModal.confirm({
        title: '提示',
        content: `取消关注后，您将无法查看或管理“${groupName}”网络！确认要取消么？`,
        async onOk() {
          const { code, msg = '取消管理分享的网络失败' } = await requestHttp({
            api: `${maccApi.CANCEL_MANAGE_SHARE_NET}?group_id=${groupId}`,
            method: 'DELETE',
          });
          if (code == 0) {
            const result = await self.getShareNetList();
            if (!result) return;
            if (!self.tenantId || self.tenantId == tenantId) {
              //当前点击 “不再管理”的网络租户是当前的租户，要重新设置默认租户
              await self.selectFirstGroupTenant();
            }

            //更新父页面的groupBar
            self.$iframeMsg('UPDATE_SHARE_NETWORK_GROUP_BAR', {
              groupId,
            });
          }
        },
      });
    },

    //进入项目
    async gotoProject(record) {
      const { groupId, tenantId } = record;
      if (this.newVueFrame) {
        this.$store.commit('Group/SET_GROUPID', groupId);
        if (
          this.theme == 'RUIYI_V2' ||
          process.env.VUE_APP_MACC_ENV == 'INTL'
        ) {
          this.$router.push('monitor_project_workbarn_menu');
        } else {
          this.$router.push('monitor_overview_networkdetails_menu');
        }
      } else {
        this.spinning = true;
        this.$iframeMsg('SWITCH_TENANT_UPDATE', {
          groupId,
          tenantId,
          jumpHome: true,
        });
      }
    },

    //修改组织名称
    async tenantChange(record, value) {
      const { code, msg = '修改项目注失败' } = await requestHttp({
        api: `${maccApi.SET_ORG_ALIAS_API.replace(
          '{tenantId}',
          record.tenantId
        )}?alias=${encodeURIComponent(value)}`,
        method: 'PUT',
        params: {
          groupId: record.groupId,
        },
      });
      if (code == 0) {
        await this.getShareNetList();
      } else {
        this.$message.error(msg);
      }
    },

    //修改网络备注
    async remarkChange(record, value) {
      const { code, msg = '修改项目备注失败' } = await requestHttp({
        api: `${maccApi.SET_NET_WORK_REMARK_API}`,
        method: 'PUT',
        params: {
          groupId: record.groupId,
          remark: value,
          tenantId: record.tenantId,
        },
      });

      if (code == 0) {
        this.tableData.forEach((item) => {
          if (item.groupId == record.groupId) {
            item.remark = value;
          }
        });
        this.tableData = [...this.tableData];
        this.zhugePoint('macc-受邀托管项目-设置备注', {
          workId: 'maccFunApply',
          funcId: 'maccShareNet',
          remark: value,
        });
      } else {
        this.$message.error(msg);
      }
    },

    //校验组织名称
    checkTenatName(rule, value, callback) {
      if (value.length == 0 || value.length > 64) {
        callback('组织名称长度不能超过64个字符');
      }
      if (value.toUpperCase() == 'ROOT') {
        callback('组织名称不能设置为ROOT');
      }
      callback();
    },

    //校验网络备注
    checkRemarkName(rule, value, callback) {
      if (value.length > 128) {
        callback('网络备注长度不能超过128个字符');
      }
      callback();
    },
  },
  watch: {
    searchKey(val) {
      if (val != '') {
        this.zhugePoint('macc-受邀托管项目-搜索', {
          workId: 'maccFunApply',
          funcId: 'maccShareNet',
          searchKey: val,
        });
      }
      this.keySearchProject();
    },
  },
};
</script>

<style lang="less" scoped>
#shareView {
  background-color: #fff;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;
  color: black;
  padding: 18px;
  box-sizing: border-box;
  .header {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .titleTxt {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .shareNetTable {
    .remarkColumns {
      width: 100%;
      text-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2; //行数
      -webkit-box-orient: vertical;
      white-space: normal;
    }
    margin-top: 15px;
    .row-name {
      font-size: 16px;
      color: #000;
    }
    .infoBlock {
      margin-right: 5px;
      color: #8c8c8c;
      background: #f5f5f5;
      padding: 2px 4px;
      line-height: 18px;
      display: flex;
      align-items: center;
      &.orgBlockStyle {
        flex: 1;
        background: transparent;
        padding: 0;
      }
      .orgBlock {
        display: flex;
        background: #f5f5f5;
        padding: 2px 4px;
        align-content: center;
        /deep/ .editable-cell {
          flex: 1;
          .user-name-bottom {
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            white-space: normal;
          }
        }
      }
    }
    .columnsName {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      cursor: pointer;
      .row-info {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-top: 5px;
        width: 100%;
      }
    }
    .columnsAction {
      color: #2b6afd;
      cursor: pointer;
    }
  }
}
</style>
